/**
 * File		: Vertex.java
 * Subject	: Represents a vertex for a shape
 * Author	: Isaac Parenteau (locus2k@gmail.com)
 * Date		: April 16th 2011
 * Note 	: Code was borrowed from Google and modified to fit the projects use
 * Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package src.project.util;

import java.nio.FloatBuffer;

public class Vertex {

	public static final String name = Vertex.class.getSimpleName();
	
	public float X;
	public float Y;
	public float Z;

	public final short Index;
	public int ColorIndex;
	
	public Color Color;
	
	/**
	 * Default constructor
	 */
	public Vertex(){ 
		this(0, 0, 0, -1); 
	}
	
	/**
	 * Constructor 
	 * @param x X coordinate
	 * @param y Y coordinate
	 * @param z Z coordinate
	 * @param index vertex index
	 */
	public Vertex(float x, float y, float z, int index){
		this.X = x;
		this.Y = y;
		this.Z = z;
		this.Index = (short)index;
	}
	
	/**
	 * Constructor that takes a vector3
	 * @param pos position of the vertex
	 * @param index index of the vertex
	 */
	public Vertex(Vector3 pos, int index){
		this.X = pos.X;
		this.Y = pos.Y;
		this.Z = pos.Z;
		this.Index = (short)index;
	}
	
	/**
	 * Puts the vertex with its color into the 
	 * vertex buffer and the color buffer
	 * @param vertexBuffer vertexBuffer to add the vertex to
	 * @param colorBuffer colorBuffer to add the color to
	 */
	public void put(FloatBuffer vertexBuffer, FloatBuffer colorBuffer){
		
		ColorIndex = colorBuffer.position();
		
		vertexBuffer.put(X);
		vertexBuffer.put(Y);
		vertexBuffer.put(Z);
		
		if(Color == null){
			for(int i = 0; i < 4; i++)
				colorBuffer.put(0);
		}
		else{
			colorBuffer.put(toFloat(Color.R));
			colorBuffer.put(toFloat(Color.G));
			colorBuffer.put(toFloat(Color.B));
			colorBuffer.put(toFloat(Color.A));
		}
	}
	
	/**
	 * converts the color integer value to float
	 * @param x int value
	 * @return float value
	 */
	private float toFloat(int x) {   	
		float value = (float)x / 255.0f;
		return value;
	}

	public void update(FloatBuffer vertexBuffer, Matrix transform) {
		vertexBuffer.position(Index * 3);
		
		if(transform == null){
			vertexBuffer.put(X);
			vertexBuffer.put(Y);
			vertexBuffer.put(Z);
		}
		else{
			Vertex temp = new Vertex();
			transform.multiply(this, temp);
			vertexBuffer.put(temp.X);
			vertexBuffer.put(temp.Y);
			vertexBuffer.put(temp.Z);
		}
	}
}
